import { BaseEntity, Column, Entity, ManyToMany, PrimaryGeneratedColumn, JoinTable } from 'typeorm';
import { User } from './user';
import { Article } from './article';

@Entity({ name: 'tags' }) // 表头名
export class Tag extends BaseEntity {
  @PrimaryGeneratedColumn()
  readonly id!: number;

  @Column()
  title!: string;

  @Column()
  icon!: string;

  @Column()
  follow_count!: number; // 有多少用户关注这个标签

  @Column()
  article_count!: number; // 文章关联数


  // 建立两个关联表: tag 和 user 的 tags_users_rel、articles_tags_rel
  @ManyToMany(() => User, {
    cascade: true // 自动保存用户关系
  })
  @JoinTable({
    name: 'tags_users_rel',
    joinColumn: {
      name: 'tag_id'
    },
    inverseJoinColumn: {
      name: 'user_id'
    }
  })
  users!: User[]

  @ManyToMany(() => Article, (article) => article.tags)
  @JoinTable({
    name: 'articles_tags_rel',
    joinColumn: {
      name: 'tag_id'
    },
    inverseJoinColumn: {
      name: 'article_id'
    }
  })
  articles!: Article[]
}
